package com.qfedu.fmmall.service.impl;

import com.qfedu.fmmall.common.status.ResStatus;
import com.qfedu.fmmall.common.vo.ResultVO;
import com.qfedu.fmmall.dao.ShoppingCartMapper;
import com.qfedu.fmmall.entity.ShoppingCart;
import com.qfedu.fmmall.service.ShoppingCartService;
import com.qfedu.fmmall.vo.ShoppingCartVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : yanBin
 * @date :2021/12/17 17:44
 */
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    private static final Logger log = LoggerFactory.getLogger(ShoppingCartServiceImpl.class);

    @Resource
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    public ResultVO addShoppingCart(ShoppingCart shoppingCart) {
        try {
            int i = shoppingCartMapper.insert(shoppingCart);
            if (i <= 0) {
                return new ResultVO(ResStatus.NO.ordinal(), "加入购物车失败", null);
            }
            return new ResultVO(ResStatus.OK.ordinal(), "加入购物车成功", null);
        } catch (Exception e) {
            log.error(e.getLocalizedMessage());
            return new ResultVO(ResStatus.NO.ordinal(), "加入购物车异常", "异常原因：" + e.getLocalizedMessage());
        }
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public ResultVO listShoppingCartByUserId(Integer userId) {
        if (userId == null) {
            return new ResultVO(ResStatus.NO.ordinal(), "查询购物车失败", null);
        }
        List<ShoppingCartVO> shoppingCartVOS = shoppingCartMapper.selectShoppingCartByUserId(userId);
        return new ResultVO(ResStatus.OK.ordinal(), "查询购物车成功", shoppingCartVOS);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public ResultVO updateCartNum(Integer cartId, String cartNum) {

       int i = shoppingCartMapper.updateByCartNum(cartId,cartNum);
        if (i <= 0) {
            return new ResultVO(ResStatus.NO.ordinal(), "更改查询数量失败", null);
        }
        return new ResultVO(ResStatus.OK.ordinal(), "更改数量成功",null);
    }

    @Override
    public ResultVO listShoppingCatByCartsId(String cartId) {
        String[] split = cartId.split(",");
        List<Integer> carts = new ArrayList<>();
        for (String s : split) {
            carts.add(Integer.valueOf(s));
        }
        List<ShoppingCartVO> shoppingCartVOS = shoppingCartMapper.selectShoppingCartByCarts(carts);
        if (CollectionUtils.isEmpty(shoppingCartVOS)){
            return new ResultVO(ResStatus.NO.ordinal(),"没有这个购物车信息",null);
        }
        return new ResultVO(ResStatus.OK.ordinal(), "查询成功",shoppingCartVOS);
    }
}
